package com.mi.rof.engineer.service.impl;

import com.mi.rof.engineer.mapper.InventoryApplyMapper;
import com.mi.rof.engineer.mapper.InventoryMapper;
import com.mi.rof.engineer.service.InventoryService;
import com.mi.rof.entity.InventoryApplyDTO;
import com.mi.rof.entity.InventoryApplyTable;
import com.mi.rof.entity.InventoryTable;
import com.mi.rof.entity.SystemException;
import com.mi.rof.entity.enums.ExceptionEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author : Yang Yu you
 */
@Service
@Slf4j
public class InventoryServiceImpl implements InventoryService {

    @Resource
    private InventoryApplyMapper inventoryApplyMapper;

    @Resource
    private InventoryMapper inventoryMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean applyInventory(InventoryApplyDTO inventoryApplyDTO) {
        Map<String, Integer> itemApply =  inventoryApplyDTO.getItemApply();
        for (Map.Entry<String, Integer> applyEntry : itemApply.entrySet()) {
            int applyResult = inventoryMapper.applyInventory(applyEntry.getKey(), applyEntry.getValue());
            if (applyResult <= 0) {
                throw new SystemException(ExceptionEnum.INVENTORY_NOT_ENOUGH.getCode(),
                        ExceptionEnum.INVENTORY_NOT_ENOUGH.getMsg());
            }
            InventoryTable inventory = inventoryMapper.selectById(applyEntry.getKey());
            InventoryApplyTable inventoryApplyTable = new InventoryApplyTable();
            inventoryApplyTable.setEngineerId(inventoryApplyDTO.getEngineerId());
            inventoryApplyTable.setRepairOrderId(inventoryApplyDTO.getRepairOrderId());
            Integer quantity = itemApply.get(applyEntry.getKey());
            inventoryApplyTable.setQuantity(quantity);
            inventoryApplyTable.setItemId(applyEntry.getKey());
            inventoryApplyTable.setItemName(inventory.getItemName());
            inventoryApplyTable.setUnitPrice(inventory.getUnitPrice());
            inventoryApplyMapper.insert(inventoryApplyTable);
        }
        return true;
    }
}
